package com.pc.fqueue.memcached;

import com.pc.fqueue.memcached.storage.FSStorage;
import com.pc.jmemcached.CacheImpl;
import com.pc.jmemcached.LocalCacheElement;
import com.pc.jmemcached.MemCacheDaemon;
import com.pc.jmemcached.storage.CacheStorage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.net.InetSocketAddress;

public class StartNewQueue {
    private static final Log log = LogFactory.getLog(StartNewQueue.class);
    
    public static void newQueueInstance(int port) { 
    	CacheStorage<String, LocalCacheElement> storage = new FSStorage();
    	newQueueInstance(port,storage);
    }

    public static void newQueueInstance(int port,CacheStorage<String, LocalCacheElement> storage) {
        InetSocketAddress addr = new InetSocketAddress("0.0.0.0", port);
        int idle = -1;
        boolean verbose = false;
        MemCacheDaemon.memcachedVersion = "0.1";
        final MemCacheDaemon<LocalCacheElement> daemon = new MemCacheDaemon<LocalCacheElement>();
        CacheImpl cacheImpl = new CacheImpl(storage);
        daemon.setCache(cacheImpl);
        daemon.setAddr(addr);
        daemon.setBinary(false);
        daemon.setIdleTime(idle);
        daemon.setVerbose(verbose);
        daemon.start();
        
        log.info("\r\n\t         FQueue instance started,port:" + port);
        
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                if (daemon != null && daemon.isRunning())
                    daemon.stop();
                log.info("shutdown server");
            }
        }));
    }
}
